﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using System.Threading;
using System.Windows.Threading;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;

namespace AzureBlobManager
{
    public partial class MainPage : UserControl
    {
        private ObservableCollection<Blob> _blobs = new ObservableCollection<Blob>();

        private IDictionary<string, string> _queryString = null;

        public MainPage()
        {
            InitializeComponent();

            _queryString = System.Windows.Browser.HtmlPage.Document.QueryString;
            InitParams.CurrentWebURI = _queryString["webUrl"];

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 1500); // 1000 Milliseconds.
            timer.Tick += new EventHandler(FetchNewBlobsToDownload);
            timer.Start();

            // Binding list of blobs for later user.
            blobList.ItemsSource = _blobs;
        }

        public void FetchNewBlobsToDownload(object sender, EventArgs e)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_FetchNewBlobsToDownloadCompleted);
            client.DownloadStringAsync(new Uri(InitParams.CurrentWebURI + "/_vti_bin/AzureBlobServices/AzureBlobService.svc/FetchBlobsToDownload?" +
                Guid.NewGuid(), UriKind.Absolute));
        }

        public void client_FetchNewBlobsToDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(e.Result);
            MemoryStream stream = new MemoryStream(bytes);
            XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfBlob));

            ArrayOfBlob array = serializer.Deserialize(stream) as ArrayOfBlob;

            if (array.Count > 0)
            {
                foreach (Blob blob in array)
                {
                    _blobs.Add(blob);
                }
            }
            stream.Close();
        }

        private void ButtonUpload_Loaded(object sender, RoutedEventArgs e)
        {
            if (!((sender as Button).Tag as Blob).IsUpload)
            {
                (sender as Button).Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void ButtonDownload_Loaded(object sender, RoutedEventArgs e)
        {
            if (((sender as Button).Tag as Blob).IsUpload)
            {
                (sender as Button).Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void ButtonUpload_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            bool? result = dialog.ShowDialog();

            if (result.Value)
            {
                Blob blob = (sender as Button).Tag as Blob;
                blob.Name = dialog.File.Name;

                IAzureTranfertManager manager = AzureTransfertFactory.GetTransferManager(blob);
                manager.Initialize(dialog.File.OpenRead(), dialog.File.Name, blob, this.Dispatcher);

                manager.StartTransfer();

                blob.StatusImage = new BitmapImage(new Uri("Images/play.png", UriKind.Relative));
                (sender as Button).IsEnabled = false;
            }
        }

        private void ButtonDownload_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            bool? result = dialog.ShowDialog();

            if (result.Value)
            {
                Blob blob = (sender as Button).Tag as Blob;

                IAzureTranfertManager manager = AzureTransfertFactory.GetTransferManager(blob);
                manager.Initialize(dialog.OpenFile(), dialog.SafeFileName, blob, this.Dispatcher);

                manager.StartTransfer();

                blob.StatusImage = new BitmapImage(new Uri("Images/play.png", UriKind.Relative));
                (sender as Button).IsEnabled = false;
            }
        }

        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            Blob blob = (sender as Button).Tag as Blob;
            blob.StatusImage = new BitmapImage(new Uri("Images/cancel.png", UriKind.Relative));
            blob.State = FileState.Cancel;
        }
    }
}
